package com.unbox.rabbit.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unbox.common.util.UnBoxUtils;
import com.unbox.common.util.UnboxLog;
import com.unbox.rabbit.comfig.RabbitConfig;
import com.unbox.rabbit.entity.Log;
import com.unbox.rabbit.service.ILogService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LogConsumer {

    @Autowired
    ILogService iLogService;

    // 国际化日志输出
    UnboxLog unboxLog = new UnBoxUtils.LocaleMessageLog(LogConsumer.class);

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitConfig.LOG_QUEUE_NAME, durable = "true"),
                    exchange = @Exchange(value = RabbitConfig.LOG_EXCHANGE, type = "fanout"))
    })
    @RabbitHandler
    public void processFanoutMsg(Message massage) {
        unboxLog.info("rabbit.consumer.log.message" ,massage.toString());
        String jsonStr = new String(massage.getBody());
        JSONObject jsonObject = (JSONObject) JSON.parse(jsonStr);
        Log log = JSON.toJavaObject(jsonObject, Log.class);
        iLogService.save(log);
    }
}
